import ApiV1WxMessagePageList_post from "@/api/ApiV1WxMessagePageList_post";
import { IRawMsg } from "@/chatlog_types/IRawMsg";
import { Chat } from "@/views/Chat";
import dayjs from "dayjs";
import { MessageLoader } from "./MessageLoader";
import { msg_adapter2 } from "./msg_adapter";

export class RemoteMessageLoader extends MessageLoader {
  static readonly TAG = 'RemoteMessageLoader';
  readonly TAG = RemoteMessageLoader.TAG
  override reset(): void { }

  override async load_news(): Promise<Chat.Message<IRawMsg>[]> {
    const { owner } = this;
    const { latest: anchor_msg } = owner
    const anchor_time = anchor_msg?.timestamp ?? Date.now();

    const start_date = dayjs(anchor_time)
    const reply = await ApiV1WxMessagePageList_post.call({
      account: this.owner.session.account,
      talker: this.owner.session.userName,
      pageNo: 1,
      pageSize: 100,
      startTime: start_date.format('YYYY-MM-DD HH:mm:ss'),
      desc: false,
    })
    if (!Array.isArray(reply.data)) {
      alert(`[${this.TAG}.load_news] reply.data got ${reply.data}! should not happen!`)
      debugger;
      return [];
    }
    const ret: Chat.Message<IRawMsg>[] = []
    for (const item of reply.data) {
      if (item.seq === anchor_msg?.raw?.seq) continue;
      ret.unshift(msg_adapter2(item))
    }
    return ret;
  }

  override async load_history(): Promise<Chat.Message<IRawMsg>[]> {
    const { earliest: anchor_msg } = this.owner
    /**
     * 锚点时间
     * 
     * 查找此时间之前的消息
     */
    const anchor_time = anchor_msg?.timestamp ?? Date.now();
    const end_date = dayjs(anchor_time);
    const reply = await ApiV1WxMessagePageList_post.call({
      account: this.owner.session.account,
      talker: this.owner.session.userName,
      pageNo: 1,
      pageSize: 100,
      endTime: end_date.format('YYYY-MM-DD HH:mm:ss'),
      desc: true,
    })
    if (!Array.isArray(reply.data)) {
      alert(`[${this.TAG}.load_history] reply.data got ${reply.data}! should not happen!`)
      debugger;
      return [];
    }
    const ret: Chat.Message<IRawMsg>[] = []
    for (const item of reply.data) {
      if (item.seq === anchor_msg?.raw?.seq) continue;
      ret.push(msg_adapter2(item))
    }
    return ret;
  }

}